package com.etc.MapReduce;

import org.apache.commons.io.FileUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.File;
import java.io.IOException;

public class Mapreduce1 {
    public static class TestMap1 extends Mapper<LongWritable, Text,Text, Text> {
        @Override
        protected void map(LongWritable key, Text value, Mapper.Context context) throws IOException, InterruptedException {
            String line = value.toString();
            String[] Array = line.split("-");
            context.write(new Text(Array[0]),new Text(Array[1].replaceAll("\t" ,"-->")));
        }
    }
    public static class TestReduce1 extends Reducer<Text, Text,Text, Text> {
        @Override
        protected void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
            String line = "";
            for(Text value : values){
                line += value.toString();
            }
            context.write(key,new Text(line));
        }
    }
    public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
        Configuration conf = new Configuration();
        //创建一个mapreduce的工作
        Job job =Job.getInstance(conf);
        job.setJarByClass(Mapreduce1.class);
        //map的class在哪里
        job.setMapperClass(Mapreduce1.TestMap1.class);
        //reduce的calss在哪里
        job.setReducerClass(Mapreduce1.TestReduce1.class);
        //map的输出类型
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(Text.class);
        //reduce的输出类型
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(Text.class);
        //判断文件是否存在，存在则删除
        File file = new File("f:\\out");
        if(file.exists()){
            FileUtils.deleteDirectory(file);
        }
        //计算的文件在哪里
        FileInputFormat.setInputPaths(job,new Path("f:\\output"));
        FileOutputFormat.setOutputPath(job,new Path("f:\\out"));

        job.waitForCompletion(true);
    }
}
